<template>
  <div>
    <div class="breadcrumb">
      <el-breadcrumb style="text-align: center" separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">考试</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">考试详情</a></el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">组卷</a></el-breadcrumb-item>
        <el-button type="primary" style="float: right" @click="confirmDialogVisible = true">提交</el-button>
<!--        <el-button type="primary" style="float: right; margin-right: 10px" @click="goToPaper(exam.id, paper.id)">预览</el-button>-->
        <el-button type="danger" style="float: right; margin-right: 10px" @click="cancelDialogVisible = true">放弃</el-button>
      </el-breadcrumb>
    </div>
    <div class="grid">
      <div class="item basic-info">
        <div>
          <div class="title"><i class="el-icon-s-order"></i>单选题(共{{paper.scoreItems.firstGroup.total}}题，每题{{paper.scoreItems.firstGroup.score}}分)</div>
          <div class="questionsBox" v-for="(question, index) in questions[0]" v-bind:key="question.id">
            <div class="question">
              <div class="text">{{index + 1}}.{{question.stem}}</div>
              <div class="text">A.{{question.options.A}} B.{{question.options.B}} C.{{question.options.C}} D.{{question.options.D}}</div>
            </div>
          </div>
        </div>
        <div class="addSquare" @click="goToAddQuestion('radio')">
          <i class="el-icon-plus text">选择题目</i>
        </div>
      </div>
      <div class="item paper">
        <div>
          <div class="title"><i class="el-icon-s-order"></i>多选题(共{{paper.scoreItems.secondGroup.total}}题，每题{{paper.scoreItems.secondGroup.score}}分)</div>
          <div class="questionsBox" v-for="(question, index) in questions[1]" v-bind:key="question.id">
            <div class="question">
              <div class="text">{{index + 1}}.{{question.stem}}</div>
<!--              <div class="text">A.{{question.options.A}} B.{{question.options.B}} C.{{question.options.C}} D.{{question.options.D}}</div>-->
            </div>
          </div>
        </div>
        <div class="addSquare" @click="goToAddQuestion('multiple')">
          <i class="el-icon-plus text">选择题目</i>
        </div>
      </div>
      <div class="item basic-info">
        <div>
          <div class="title"><i class="el-icon-s-order"></i>填空题(共{{paper.scoreItems.thirdGroup.total}}题，每题{{paper.scoreItems.thirdGroup.score}}分)</div>
          <div class="questionsBox" v-for="(question, index) in questions[2]" v-bind:key="question.id">
            <div class="question">
              <div class="text">{{index + 1}}.{{question.stem}}</div>
            </div>
          </div>
        </div>
        <div class="addSquare" @click="goToAddQuestion('filling')">
          <i class="el-icon-plus text">选择题目</i>
        </div>
      </div>
      <div class="item paper">
        <div>
          <div class="title"><i class="el-icon-s-order"></i>简答题(共{{paper.scoreItems.forthGroup.total}}题，每题{{paper.scoreItems.forthGroup.score}}分)</div>
          <div class="questionsBox" v-for="(question, index) in questions[3]" v-bind:key="question.id">
            <div class="question">
              <div class="text">{{index + 1}}.{{question.stem}}</div>
            </div>
          </div>
        </div>
        <div class="addSquare" @click="goToAddQuestion('shortAnswer')">
          <i class="el-icon-plus text">选择题目</i>
        </div>
      </div>
    </div>
    <!--  确定  -->
    <el-dialog
      title="提示"
      :visible.sync="confirmDialogVisible"
      width="30%">
      <span>确定添加题目至试卷吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="confirmDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addQuestionToPaper">确 定</el-button>
      </span>
    </el-dialog>
    <!--  取消  -->
    <el-dialog
      title="提示"
      :visible.sync="cancelDialogVisible"
      width="30%">
      <span>确定放弃添加题目到试卷吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelDialogVisible = false">取 消</el-button>
        <el-button type="danger" @click="clearQuestion">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {getPaper, getExamById, addQuestionToPaper} from '../../../api/exam'
import {queryById} from '../../../api/questions'

export default {
  name: 'QuestionAdd',
  data () {
    return {
      // 确认提交
      confirmDialogVisible: false,
      cancelDialogVisible: false,
      // 考试id
      examId: 0,
      // 考试
      exam: {
        createTime: '2022-04-02 15:54:34',
        endTime: '2022-04-03 04:00:00',
        id: 10,
        name: '2022软件工程考试',
        startTime: '2022-04-03 02:00:00',
        status: '未发布',
        subjectId: 8,
        teacherId: 4,
        updateTime: '2022-04-02 15:54:34'
      },
      // 考试试卷
      paper: {
        createTime: '2022-04-02 15:59:13',
        examId: 10,
        id: 9,
        questionOrder: null,
        scoreItems: null,
        questionOrderJSONStr: '[]',
        scoreItemsJSONStr: '{"firstGroup":{"questionType":"radio","score":2,"total":10},"secondGroup":{"questionType":"multiple","score":4,"total":5},"thirdGroup":{"questionType":"filling","score":4,"total":5},"forthGroup":{"questionType":"shortAnswer","score":10,"total":4}}',
        updateTime: '2022-04-02 15:59:13'
      },
      // 试卷题目
      questions: [
        [],
        [],
        [],
        []
      ]
    }
  },
  mounted () {
    this.examId = this.$route.query.examId
    this.getPaper(this.examId)
    this.getExam(this.examId)
    this.getQuestions()
  },
  methods: {
    // 跳转试卷预览
    goToPaper (examId, paperId) {
      console.log(paperId)
      this.$router.push({path: '/exam/paper', query: {examId: examId, paperId: paperId}})
    },
    // 提交题目
    addQuestionToPaper () {
      let order = JSON.parse(sessionStorage.getItem('questionOrder'))
      // 判断题目是否足够
      let flag = this.paper.scoreItems.firstGroup.total === order[0].length &&
        this.paper.scoreItems.secondGroup.total === order[1].length &&
        this.paper.scoreItems.thirdGroup.total === order[2].length &&
        this.paper.scoreItems.forthGroup.total === order[3].length

      if (!flag) {
        this.$message.error('请加入正确的题目数量！')
      } else {
        let ids = []
        for (let i = 0; i < order.length; i++) {
          for (let j = 0; j < order[i].length; j++) {
            ids.push(order[i][j])
          }
        }
        let info = {
          paperId: this.paper.id,
          questionOrder: JSON.parse(sessionStorage.getItem('questionOrder')),
          questionId: ids
        }
        addQuestionToPaper(info).then(res => {
          console.log(res.data)
          if (res.data.errorCode === 0) {
            this.$message.success('添加成功！')
            this.confirmDialogVisible = false
            // 清空缓存
            sessionStorage.setItem('questionOrder', JSON.stringify([[], [], [], []]))
            // 跳转预览
            this.$router.go(-1)
          } else {
            this.$message.error(res.data.message)
          }
        })
      }
    },
    // 通过前端存储的题目id获取题目
    getQuestions () {
      let order = JSON.parse(sessionStorage.getItem('questionOrder'))
      // let order = [[33, 34], [32, 35], [], [36]]
      if (order !== null) {
        for (let i = 0; i < order.length; i++) {
          for (let j = 0; j < order[i].length; j++) {
            console.log('order' + order[i][j])
            queryById(order[i][j]).then(res => {
              if (res.data.errorCode === 0) {
                this.questions[i][j] = res.data.data.list[0]
                console.log('question' + this.questions[i][j].id)
                this.questions[i][j].stem = JSON.parse(this.questions[i][j].questionStem).stem
                this.questions[i][j].options = JSON.parse(this.questions[i][j].questionStem).options
                this.$forceUpdate()
              } else {
                this.$message.error(res.data.message)
              }
            })
          }
        }
      }
    },
    // 获取前端存储的题目id
    getQuestionOrder () {
      console.log(sessionStorage.getItem('questionOrder'))
      if (sessionStorage.getItem('questionOrder') === null) {
        sessionStorage.setItem('questionOrder', JSON.stringify([[], [], [], []]))
      }
    },
    // 跳转选择题目页面
    goToAddQuestion (questionType) {
      this.getQuestionOrder()
      this.$router.push({path: '/exam/questionForPaper', query: {subjectId: this.exam.subjectId.toString(), questionType: questionType}})
    },
    // 获取试卷
    getPaper (examId) {
      getPaper(examId).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.paper = res.data.data.list[0]
          this.paper.questionOrder = JSON.parse(this.paper.questionOrderJSONStr)
          this.paper.scoreItems = JSON.parse(this.paper.scoreItemsJSONStr)
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 获取考试
    getExam (examId) {
      getExamById(examId).then(res => {
        console.log(res.data)
        if (res.data.errorCode === 0) {
          this.exam = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    // 清除所有题目
    clearQuestion () {
      sessionStorage.setItem('questionOrder', JSON.stringify([[], [], [], []]))
      this.getQuestions()
      this.cancelDialogVisible = false
      // 需要跳转
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped>
  .breadcrumb {
    padding: 20px;
  }

  .grid{
    padding: 20px;
    display: grid;
    grid-template-columns: 50% 50%;
    grid-auto-flow: row dense;
  }

  .item {
    text-align: left;
    border: 1px solid #e5e4e9;
    position: relative;
    padding: 10px 10px 100px;
  }

  .title {
    margin-top: 20px;
    margin-left: 20px;
    font-size: 20px;
    font-weight: bolder;
  }

  .text {
    margin-top: 10px;
    margin-bottom: 10px;
    margin-left: 20px;
    font-size: 15px;
  }

  .basic-info {
    height: auto;
    grid-column-start: 1;
    grid-column-end: 2;
  }

  .paper {
    height: auto;
    grid-column-start: 2;
    grid-column-end: 3;
  }

  /* 题目卡片 */
  .questionsBox {
    padding: 2px;
    display: grid;
    grid-template-columns: 90%;
  }

  .questionsBox .question {
  }

  .questionsBox .button {
    margin-top: 10%;
    height: 30px;
    width: 60px;
    text-align: center;
  }

  /* 增加框 */
  .addSquare {
    margin-left: 20%;
    width: 60%;
    height: 60px;
    background: #e8e8e8;
    border-radius: 20px;
    position: absolute;
    bottom: 20px;
  }

  .addSquare .text {
    width: 60%;
    margin-left: 27%;
    margin-top: 15px;
    font-size: 25px;
    font-weight: bolder;
    color: #7a7c7f;
  }
</style>
